package com.shanyi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shanyi.common.util.UuidStringUtil;
import com.shanyi.dao.entity.TravelAddressDetailEntity;
import com.shanyi.dao.mapper.TravelAddressDetailMapper;
import com.shanyi.dao.req.AddCountReqDto;
import com.shanyi.dao.req.TravelInfoListReqDto;
import com.shanyi.dao.req.TravelInfoReqDto;
import com.shanyi.service.TravelService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @Author shanyi
 * @Date 2023/2/17 15:30
 */
@Service
public class TravelServiceImpl implements TravelService {
    
    @Resource
    private TravelAddressDetailMapper travelAddressDetailMapper;
    
    @Override
    public Page<TravelAddressDetailEntity> getTravelInfoList(TravelInfoListReqDto dto) {

        Page<TravelAddressDetailEntity> page = new Page<>(dto.getPage(), dto.getPageSize());

        LambdaQueryWrapper<TravelAddressDetailEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(TravelAddressDetailEntity::getCity,dto.getCity());
        Page<TravelAddressDetailEntity> entityPage = travelAddressDetailMapper.selectPage(page, wrapper);
        
        return entityPage;
    }

    @Override
    public String addTravelInfo(TravelInfoReqDto dto) {

        if (checkExist(dto.getProvince(), dto.getCity())) {
            return "success";
        }

        String uuid = UuidStringUtil.get32UUID();
        TravelAddressDetailEntity entity = new TravelAddressDetailEntity(uuid, dto.getProvince(), dto.getCity(), dto.getVisitCount(), dto.getVisitReason(), dto.getFirstTime());
        int insert = travelAddressDetailMapper.insert(entity);
        
        if (insert == 1) {
            return "success";
        }
        return "fail";
    }

    @Override
    public String addCount(AddCountReqDto dto) {

        LambdaQueryWrapper<TravelAddressDetailEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TravelAddressDetailEntity::getCityCode,dto.getCityCode());
        Long count = travelAddressDetailMapper.selectCount(wrapper);

        if (count == 1) {
            travelAddressDetailMapper.addCount(dto.getCityCode());
        }

        return dto.getCityCode() ;
    }

    private boolean checkExist(String province, String city) {
        LambdaQueryWrapper<TravelAddressDetailEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TravelAddressDetailEntity::getProvince, province);
        wrapper.eq(TravelAddressDetailEntity::getCity, city);
        return travelAddressDetailMapper.exists(wrapper);
    }
}
